package com.yan_jiu_sheng.LeetCodeHot100;

/**
 * https://leetcode.cn/problems/word-search/description/?envType=study-plan-v2&envId=top-100-liked
 * 感觉系统判题有误
 * ABCESEEEFS   其中一个e被重复使用了
 *
 * @author yulongTian
 * @create 2024-07-08 13:56
 */
public class Test60 {
    public static void main(String[] args) {
//        char[][] board = {
//                {'A', 'B', 'C', 'E'},
//                {'S', 'F', 'C', 'S'},
//                {'A', 'D', 'E', 'E'}
//        };
//        char[][] board = {
//                {'C', 'A', 'A'},
//                {'A', 'A', 'A'},
//                {'B', 'C', 'D'}
//        };
        char[][] board = {
                {'A', 'B', 'C', 'E'},
                {'S', 'F', 'E', 'S'},
                {'A', 'D', 'E', 'E'}
        };
//        String word = "ABCCED";
//        String word = "SEE";
        String word = "ABCESEEEFS";
        System.out.println(new Test60().exist(board, word));
    }

    boolean ans = false;

    public boolean exist(char[][] board, String word) {
        int m = board.length;
        int n = board[0].length;
        int word_index = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                boolean[][] visited = new boolean[m][n];
                boolean[] flag = new boolean[word.length()];
                dfs(i, j, word, word_index, flag, board, visited);
            }
        }
        return ans;
    }

    public void dfs(int cur_i, int cur_j, String word,
                    int word_index, boolean[] flag, char[][] board, boolean[][] visited) {
        if (visited[cur_i][cur_j]) {
            return;
        }
        if (board[cur_i][cur_j] == word.charAt(word_index)) {
            visited[cur_i][cur_j] = true;
            flag[word_index] = true;
            if (word_index == word.length() - 1) {
                ans = true;
                return;
            }
        } else {
            return;
        }

        // 上
        if (cur_i - 1 >= 0) {
            dfs(cur_i - 1, cur_j, word, word_index + 1, flag, board, visited);
        }

        // 下
        if (cur_i + 1 < board.length) {
            dfs(cur_i + 1, cur_j, word, word_index + 1, flag, board, visited);
        }

        // 左
        if (cur_j - 1 >= 0) {
            dfs(cur_i, cur_j - 1, word, word_index + 1, flag, board, visited);
        }

        // 右
        if (cur_j + 1 < board[0].length) {
            dfs(cur_i, cur_j + 1, word, word_index + 1, flag, board, visited);
        }
    }

}
